<script setup lang="ts">
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useFs } from '@fast-crud/fast-crud';

import { ExtendMsgConfig } from '#/api/basic/msg/extendMsg';
import { getValidateRulesByFs } from '#/api/common/validateByFs';
import { ActionEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';

import { createCrudOptions, frontRules } from '../data/send-crud';

defineOptions({
  name: '测试发送消息',
  inheritAttrs: false,
});

const emit = defineEmits<Emits>();
interface Emits {
  (e: 'success'): void;
}
const formRef = ref();
const { createMessage } = useMessage();

const { crudBinding, appendCrudOptions } = useFs({ createCrudOptions });

const [Modal, modalApi] = useVbenModal({
  async onOpened() {
    modalApi.setState({ loading: false, confirmLoading: false });
    // 赋值
    const record = { ...modalApi.getData()?.row };
    formRef.value.setFormData(record, { mergeForm: false });

    const validateApi = ExtendMsgConfig.SendByTemplate;
    const addFormOptions = await getValidateRulesByFs({
      Api: validateApi,
      mode: ActionEnum.ADD,
      customRules: frontRules(ActionEnum.ADD),
    });
    appendCrudOptions({ ...addFormOptions });
  },
  async onConfirm() {
    try {
      modalApi.setState({ loading: true, confirmLoading: true });
      await formRef.value.submit();

      createMessage.success('发送成功');
      modalApi.close();
      emit('success');
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
});

defineExpose(modalApi);
</script>

<template>
  <Modal class="w-[60%]" title="测试发送">
    <div class="p-4">
      <FsForm ref="formRef" v-bind="crudBinding.addForm" />
    </div>
  </Modal>
</template>

<style lang="scss" scoped>
::v-deep(.vxe-buttons--wrapper:not(:empty)) {
  padding-top: 0;
}
</style>
